﻿using System;
using System.IO;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Resources;

using CE.User;
using CE.Global;
using CE.Database;
using CE.CarInsurance;

public partial class SiteUser_CarInsurance_ViewCICustomerCallNew : System.Web.UI.Page
{
    int _currentRow = 0;
    private DateTime dateTimeNow = CE.Global.General.GetUTCDateTime();

    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session[CE.Global.General.UserId] == null)
        {
            Response.Redirect("~/SiteUserSecureLogin.aspx");
        }

        if (Request.Params["calltype"] != null)
        {
            if (Request.Params["calltype"] == "100" || Request.Params["calltype"] == "101")
            {
                lblCallType.Text = Request.Params["calltype"].ToString();
                if (lblCallType.Text == "100")
                {
                    
                    lblCallTypeDesc.Text = Resources.General.FirstFollowUpCall;
                    lblLastCallStatusCaption.Text = Resources.General.FirstFollowUpCall + " - " + Resources.General.LastCallStatus;
                }
                else
                {
                    lblCallTypeDesc.Text = Resources.General.CallMeRequest;
                    lblLastCallStatusCaption.Text = Resources.General.CallMeRequest + " - " + Resources.General.LastCallStatus;
                }
            }
            else
            {
                Response.Redirect("~/SiteUserHome.aspx");
            }
        }
        else
        {
            Response.Redirect("~/SiteUserHome.aspx");
        }

        if (!IsPostBack)
        {
            DateTime time = dateTimeNow;
            lblStartDateTime.Text = time.ToString("dd/MMM/yyyy hh:mm:ss tt"); //Don't use HTML tag inside text
            lblStartDayName.Text = "<b style='color:red;'>" + time.ToString("dddd") + " </b>";
            hplReRunQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmReRunQuoteMessage + "');");
            hplNewQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.General.ConfirmRunNewQuoteMessage + "');");
            hplOfflineQuote.Attributes.Add("onclick", "javascript:return confirm('" + Resources.CarInsurance.ConfirmToGoNonGGPackages + "');");

            if (Request.Params["buynowrefresh"] != null)
            {
                if (Request.Params["buynowrefresh"].ToString() == "true")
                {
                    if (Session[General.CallPageStartDateTime] != null)
                    {
                        time = Convert.ToDateTime(Session[General.CallPageStartDateTime].ToString());
                        lblStartDateTime.Text = time.ToString("dd/MMM/yyyy hh:mm:ss tt"); //Don't use HTML tag inside text
                        lblStartDayName.Text = "<b style='color:red;'>" + time.ToString("dddd") + " </b>";
                        GetCallDuration();
                    }
                }
            }
            else
            {
                Session[General.CallPageStartDateTime] = null;
                Session[General.BuyNowCarID] = null;
            }

            lblResetUrl.Text = Request.Url.ToString();
            ResetAll();
            txtAgentId.Text = Session[General.UserId].ToString();
            LoadAgentList();
            for (int i = 2012; i <= dateTimeNow.Year + 1; i++)
            {
                ddlTYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                ddlTYear.Text = dateTimeNow.Year.ToString();
                ddlTDay.Text = dateTimeNow.AddDays(1).ToString();
                ddlTMonth.Text = dateTimeNow.Month.ToString("00");
            }

            ddlCIMainCallStatus.Items.Clear();
            ddlCICallStatus.Items.Clear();
            rdoCallFinish.Checked = true;
            rdoCallFinish_CheckedChanged(sender, e);

            if (ddlCIMainCallStatus.Items.Count > 0)
            {
                ddlCIMainCallStatus.SelectedIndex = 0;
                ddlCIMainCallStatus_SelectedIndexChanged(sender, e);
            }

            if (Request.Params["leadid"] != null && Request.Params["calltype"] != null)
            {
                Int64 _leadId = 0;
                Int16 _callType = 0;

                if (Int64.TryParse(Request.Params["leadid"].ToString(), out _leadId) && Int16.TryParse(Request.Params["calltype"].ToString(), out _callType))
                {
                    if (!ShowScreen(_leadId, _callType))
                    {
                        
                        lblCallSessionName.Text = Resources.General.NORECORDFOUND;
                        ResetAll();
                    }
                }
                else
                {
                    Response.Redirect("~/SiteUserHome.aspx");
                }
            }
            else if (!ShowScreen())
            {
               
                lblCallSessionName.Text = Resources.General.NoMoreCallForYou.ToUpper();
                ResetAll();
            }
        }
    }

    private void LoadAgentList()
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            DataTable _dt = new DataTable("tblList");
            string _spName = "sprocCXCRMGetAgentList";

            _dt = _db.GetDataTable(_spName);
            ddlCBAgentList.Items.Clear();
            if (_dt != null && _dt.Rows.Count > 0)
            {
                ddlCBAgentList.DataSource = _dt;
                ddlCBAgentList.DataTextField = "FULLNAME";
                ddlCBAgentList.DataValueField = "CEID";
                ddlCBAgentList.DataBind();
            }
        }
        catch (Exception Ex)
        {
            
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadAgentList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    private void ShowOfflinePackageCount()
    {
       
        try
        {
            string spName = "sprocCXBrokerPremiumSelectItemCount";
            MyDatabase _db = new MyDatabase();
            SortedList _paraList = new SortedList();
            _paraList.Add("@CECarId", txtCarId.Text);
            _paraList.Add("@ProductType", "CIN");
            object _objCount = new object();
            _objCount = _db.ExecuteScalarSP(spName, _paraList);
            int _offlineCount = 0;
            if (_objCount != null)
            {
                _offlineCount = Convert.ToInt32(_objCount);
            }

            if (_offlineCount > 0)
            {
                hplOfflineQuote.Text = Resources.CarInsurance.UpdateNonGGPackage;
                lblOfflineQuoteCount.Text = "(" + _offlineCount.ToString() + ") " + Resources.CarInsurance.NonGGPacakagesFound;
                hplOfflineQuote.Text += " <b style='color:#FCB200;'>(" + _offlineCount.ToString() + ") " + Resources.CarInsurance.NonGGPacakagesFound + "</b>";
                divPremiumList.Visible = true;

                SetGVPremiumSelectedIndex();
            }
            else
            {
                lblAppStatusMessage.Text = string.Empty;
                hplOfflineQuote.Text = Resources.CarInsurance.CreateNonGGPackage;
                lblOfflineQuoteCount.Text = "";
                divPremiumList.Visible = false;
            }

        }
        catch (Exception Ex)
        {

            throw;
        }
    }

    private bool ShowScreen(Int64 AgentLeadID, Int16 CallType)
    {
        bool _retValue = false;
        try
        {
            string _spName = "sprocCXCRMGetCarDetailSelectSingleItemByAgentLeadID";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentLeadID", AgentLeadID);
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);
            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {
                lblAgentLeadID.Text = _dtCarDetail.Rows[0][0].ToString();
                txtCustomerId.Text = _dtCarDetail.Rows[0][1].ToString();
                divCarDetailList.Visible = true;
                gvCarDetailList.DataBind();

                

                if (Session[General.BuyNowCarID] != null)
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(Session[General.BuyNowCarID].ToString()));
                }
                else
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(_dtCarDetail.Rows[0][2].ToString()));
                }

                if (lblCallType.Text == "101")
                {
                    txtCallMeId.Text = " - " + _dtCarDetail.Rows[0][5].ToString();
                    lblCallSessionName.Text += " - " + Resources.CarInsurance.CarId + ":<b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.CarInsurance.CallTime + ":<b style='color:green;'>" + _dtCarDetail.Rows[0][6].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.CarInsuranceResultPage.Insurer + ":<b style='color:blue;'>" + _dtCarDetail.Rows[0][9].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.General.Requestedon + ":<b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][7].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b>";
                }

                CheckApplicationStatus();

                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen(Int64 AgentLeadID, Int16 CallType)<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
           
        }

        return _retValue;
    }

    private bool ShowScreen()
    {
        bool _retValue = false;
        try
        {
            string _spName = "sprocCXCRMGetCarDetailSelectSingleItem";
            MyDatabase _db = new MyDatabase();
            DataTable _dtCarDetail = new DataTable("tblCar");
            SortedList _paraList = new SortedList();
            _paraList.Add("@AgentID", Session[General.UserId].ToString());
            _paraList.Add("@CallType", lblCallType.Text);
            _paraList.Add("@LangOption", lblLangOption.Text);

            _dtCarDetail = _db.GetDataTableBySP(_spName, _paraList);
            if (_dtCarDetail != null && _dtCarDetail.Rows.Count > 0)
            {
                lblAgentLeadID.Text = _dtCarDetail.Rows[0][0].ToString();
                txtCustomerId.Text = _dtCarDetail.Rows[0][1].ToString();
                divCarDetailList.Visible = true;
                gvCarDetailList.DataBind();
                
                if (Session[General.BuyNowCarID] != null)
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(Session[General.BuyNowCarID].ToString()));
                }
                else
                {
                    SetGVCarDetailSelectedIndex(Convert.ToInt64(_dtCarDetail.Rows[0][2].ToString()));
                }

                if (lblCallType.Text == "101")
                {
                    txtCallMeId.Text = _dtCarDetail.Rows[0][5].ToString();

                    lblCallSessionName.Text += " - " + Resources.CarInsurance.CarId + ":<b style='color:red;'>" + _dtCarDetail.Rows[0][2].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.CarInsurance.CallTime + ":<b style='color:green;'>" + _dtCarDetail.Rows[0][6].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.CarInsuranceResultPage.Insurer + ":<b style='color:blue;'>" + _dtCarDetail.Rows[0][9].ToString() + "</b>";
                    lblCallSessionName.Text += " - " + Resources.General.Requestedon + ":<b style='color:red;'>" + Convert.ToDateTime(_dtCarDetail.Rows[0][7].ToString()).ToString("dd/MMM/yyyy hh:mm:ss tt") + "</b>";
                }

                CheckApplicationStatus();
                _retValue = true;
            }
            else
            {
                _retValue = false;
            }
        }
        catch (Exception Ex)
        {
            _retValue = false;
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at ShowScreen()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
           
        }

        return _retValue;
    }

    protected void ShowCarAndCustomerDetails(Int64 CustomerID, Int64 CarID, Int64 CarPolicyID)
    {
        if (CustomerID > 0 && CarID > 0 && CarPolicyID > 0)
        {
            txtCustomerId.Text = CustomerID.ToString();
            txtCarId.Text = CarID.ToString();
            txtCarPolicyId.Text = CarPolicyID.ToString();
            
            txtCallStatusId.Text = "0";
            ddlCICallStatus.Text = "-1";
            txtCICallMeRemark.Visible = false;
            lblRefCarID.Text = CarID.ToString();

            MyDatabase _myDb = new MyDatabase();
            Int64 _providerCompanyId = 0;
            object _objPID = _myDb.ExecuteScalarSqlStatement("select ProviderCompanyID from tblCarInsuranceSelectItemTH Where CarID = " + txtCarId.Text + " And RefCEUserID = " + txtCustomerId.Text);

            if (_objPID != null)
            {
                _providerCompanyId = Convert.ToInt64(_objPID);

                SortedList _sqlParam = new SortedList();
                _sqlParam.Add("@CarID", txtCarId.Text);
                _sqlParam.Add("@ProviderCompanyID", _providerCompanyId.ToString());
                DataTable _dtCompltedQuote = _myDb.GetDataTableBySP("sprocCarInsuranceTHCompletedUserSelectItem", _sqlParam);

                if (_dtCompltedQuote != null && _dtCompltedQuote.Rows.Count > 0)
                {
                    divPremiumList.Visible = false;
                    divCompletedQuoteDetails.Visible = true;
                    hplNewQuote.Enabled = false;
                    hplReRunQuote.Enabled = false;
                    
                    divLinks.Visible = true;
                    hplOfflineQuote.NavigateUrl = "~/carinsurance/offline/ViewCINoMatchFound.aspx?leadid=" + lblAgentLeadID.Text + "&calltype=" + lblCallType.Text + "&carid=" + txtCarId.Text + "&custid=" + txtCustomerId.Text;
                    ShowOfflinePackageCount();
                
                    gvCarResult.DataSource = null;
                    gvCarResult.DataBind();
                    divResult.Visible = false;
                    divCallHistory.Visible = true;
                    lblCQFullName.Text = _dtCompltedQuote.Rows[0][0].ToString();
                    lblCQQuoteRefNo.Text = _dtCompltedQuote.Rows[0][2].ToString();
                    lblCQCustomerAddress.Text = _dtCompltedQuote.Rows[0][3].ToString();
                    lblCQPaymentType.Text = _dtCompltedQuote.Rows[0][4].ToString();

                    lblCQOrderRefNo.Text = _dtCompltedQuote.Rows[0][5].ToString();
                    lblCQPackageName.Text = _dtCompltedQuote.Rows[0][6].ToString();
                    lblCQPremiumAmount.Text = _dtCompltedQuote.Rows[0][7].ToString();
                    lblCQCarMakeModelDesc.Text = _dtCompltedQuote.Rows[0][8].ToString();
                    lblCQDateTime.Text = Convert.ToDateTime(_dtCompltedQuote.Rows[0][10].ToString()).ToString("dd-MMM-yyyy hh:mm:ss tt");
                    lblCQPaymentGateWayStatus.Text = _dtCompltedQuote.Rows[0][11].ToString();
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert(' " + Resources.CarInsurance.ReferenceNo + ". \"" + lblCQQuoteRefNo.Text + "\" >> " + Resources.CarInsurance.CarId + ": " + txtCarId.Text + " - " + Resources.General.ApplicationFormSummary + "" + "');", true);
                    
                }
            }

            if (_providerCompanyId <= 0)
            {
                divCompletedQuoteDetails.Visible = false;
                hplNewQuote.Visible = true;
                hplReRunQuote.Visible = true;
                divResult.Visible = true;
                divLinks.Visible = true;
                divCallHistory.Visible = true;
                string carInsuranceURL = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CIServerPath");
                string paInsuranceURL = CE.Configuration.MyConfigurationManager.GetAppSettingValue("PAServerPath");
                hplNewQuote.NavigateUrl = carInsuranceURL + "AgentLogin.aspx?uid=" + Session[General.UserId].ToString() +
                                    "&cid=" + txtCustomerId.Text + "&pcid=-1"; //+ ddlProviderCompany.Text;
                hplReRunQuote.NavigateUrl = carInsuranceURL + "AgentLogin.aspx?uid=" + Session[General.UserId].ToString() + "&carid=" + txtCarId.Text + "&policyid=" + txtCarPolicyId.Text +
                                    "&cid=" + txtCustomerId.Text + "&pcid=-1"; //+ ddlProviderCompany.Text;
                hplOfflineQuote.NavigateUrl = "~/carinsurance/offline/ViewCINoMatchFound.aspx?leadid=" + lblAgentLeadID.Text + "&calltype=" + lblCallType.Text + "&carid=" + txtCarId.Text + "&custid=" + txtCustomerId.Text;
                ShowOfflinePackageCount();
                txtServerPath.Text = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CIProposalServerPath");

                ResultsQuotesDataBind();


                
                gvCarResult.Sort("AnnualPremium", SortDirection.Ascending);
                gvCarResult.SelectedIndex = 0;
                txtCarResultId.Text = "0";
                txtCXCRMId.Text = "0";
                txtCICallMeRemark.Text = "";
                lblCallStatusMessage.Text = "";
                ddlCICallStatus.Text = "-1";
                txtCallStatusId.Text = "0";
                if (txtCustomerId.Text != string.Empty && txtCarId.Text != string.Empty)
                {
                    MyDatabase _db = new MyDatabase();
                    //Customer Details
                    string _strSelect = "select P.FirstName, P.SurName, P.DOB, P.Gender, C.Email, C.Mobile, O.TH Occupation from tblCEUsrProfile P "
                                        + "INNER JOIN tblOccupationInfo O ON P.Occupation = O.OccupationId "
                                        + "INNER JOIN tblCEContact C ON C.RefCEUserID = P.RefCEUserID "
                                        + "Where P.RefCEUserId = " + txtCustomerId.Text;
                    DataTable _dtSelect = new DataTable("dtSelect");
                    _dtSelect = _db.GetDataTable(_strSelect);
                    if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                    {
                        lblName.Text = _dtSelect.Rows[0]["FirstName"].ToString();
                        lblLastName.Text = _dtSelect.Rows[0]["SurName"].ToString();
                        lblGender.Text = _dtSelect.Rows[0]["Gender"].ToString() == "M" ? "ชาย" : "หญิง";
                        lblDOB.Text = Convert.ToDateTime(_dtSelect.Rows[0]["DOB"].ToString()).ToString("dd/MMM/yyyy");
                        lblOccupation.Text = _dtSelect.Rows[0]["Occupation"].ToString();
                        lblMobileNo.Text = _dtSelect.Rows[0]["Mobile"].ToString();
                        lblRefMobile.Text = lblMobileNo.Text;
                        lblEmailAddress.Text = _dtSelect.Rows[0]["Email"].ToString();
                        lblRefEmail.Text = lblEmailAddress.Text;
                    }
                    _dtSelect = null;
                    _dtSelect = new DataTable("dtSelect");

                    _strSelect = " Select CD.MakeModelDesc, CD.ManufactYear, P.TH CurrentInsurer "
                                + " from tblCarDetailTH CD"
                                + " INNER JOIN tblPreInsurer P ON CAST(CD.Info1 AS INT) = P.PreInsurerId"
                                + " Where P.CompanyType = 1 And P.ServiceType = 100 AND CD.RefCEUserId = " + txtCustomerId.Text + " And CD.CarId= " + txtCarId.Text;
                    _dtSelect = _db.GetDataTable(_strSelect);
                    if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                    {
                        lblCarMakeModel.Text = _dtSelect.Rows[0]["MakeModelDesc"].ToString();
                        lblRegYear.Text = _dtSelect.Rows[0]["ManufactYear"].ToString();
                        lblCurrentInsurer.Text = _dtSelect.Rows[0]["CurrentInsurer"].ToString();

                    }

                    _dtSelect = null;
                    _dtSelect = new DataTable("dtSelect");
                    bool _IsClaim = false;
                    bool _IsAddDriver = false;
                    string _vehicleType;
                    DateTime _dtCoverCommDate = dateTimeNow;
                    _strSelect = "Select InsuranceType, GarageType, VehicleType, SumInsured, NCDPercent, IsClaimLastYear, IsCTPL , IsAddDriver, NoOfDriver, CoverageCommenceDate, ModifiedDate "
                        + " from tblCarPolicy"
                        + " Where RefCEUserId = " + txtCustomerId.Text + " And CECarId= " + txtCarId.Text;
                    _dtSelect = _db.GetDataTable(_strSelect);
                    if (_dtSelect != null && _dtSelect.Rows.Count > 0)
                    {
                        lblInsuranceType.Text = "";
                        string _strInsType = _dtSelect.Rows[0]["InsuranceType"].ToString().Substring(0, 2);
                        if (_strInsType == "10")
                        {
                            lblInsuranceType.Text = "1";
                        }
                        else if (_strInsType == "11")
                        {
                            lblInsuranceType.Text = "1+";
                        }
                        else if (_strInsType == "21")
                        {
                            lblInsuranceType.Text = "2+";
                        }
                        else if (_strInsType == "30")
                        {
                            lblInsuranceType.Text = "3";
                        }
                        else if (_strInsType == "31")
                        {
                            lblInsuranceType.Text = "3+";
                        }
                        lblGarageType.Text = _dtSelect.Rows[0]["GarageType"].ToString() == "1" ? "อู่ประกัน" : "อู่ห้าง";
                        _vehicleType = _dtSelect.Rows[0]["VehicleType"].ToString();
                        switch (_vehicleType)
                        {
                            case "110":
                                lblVehicleType.Text = "รถยนต์ส่วนบุคคล";
                                break;
                            case "120":
                                lblVehicleType.Text = "รถสาธารณะ";
                                break;
                            default:
                                lblVehicleType.Text = _vehicleType;
                                break;
                        }

                        string _strQuoteDate = _dtSelect.Rows[0]["ModifiedDate"].ToString();
                        DateTime _dtQuoteDate = dateTimeNow;
                        DateTime _dtCompareQuoteDate = dateTimeNow.AddMonths(-1);
                        if (DateTime.TryParse(_strQuoteDate, out _dtQuoteDate))
                        {
                            lblRefModifiedDateTime.Text = _dtQuoteDate.ToString("dd/MMM/yyyy hh:mm tt");
                            if (DateTime.Compare(_dtCompareQuoteDate, _dtQuoteDate) > 0)
                            {
                                lblQuoteDateTimeStatus.Text = "0";
                                lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOVER;
                                lblQuoteDateTimeStatusMessage.Font.Bold = true;
                                lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                            }
                            else
                            {
                                lblQuoteDateTimeStatus.Text = "1";
                                lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeOK;
                                lblQuoteDateTimeStatusMessage.Font.Bold = true;
                                lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Green;
                            }
                        }
                        else
                        {
                            lblQuoteDateTimeStatus.Text = "0";
                            lblQuoteDateTimeStatusMessage.Text = Resources.General.QuoteDateTimeNOTVALID;
                            lblQuoteDateTimeStatusMessage.Font.Bold = true;
                            lblQuoteDateTimeStatusMessage.ForeColor = System.Drawing.Color.Red;
                        }

                        lblSumInsured.Text = Convert.ToInt32(_dtSelect.Rows[0]["SumInsured"]).ToString("#,000");
                        lblNCD.Text = _dtSelect.Rows[0]["NCDPercent"].ToString() == "-1" ? "0" : _dtSelect.Rows[0]["NCDPercent"].ToString() + "%";

                        lblCTPL.Text = Convert.ToBoolean(_dtSelect.Rows[0]["IsCTPL"]) == true ? "ใช่" : "ไม่ต้องการ";
                        _IsClaim = Convert.ToBoolean(_dtSelect.Rows[0]["IsClaimLastYear"].ToString());
                        _IsAddDriver = Convert.ToBoolean(_dtSelect.Rows[0]["IsAddDriver"].ToString());
                        string _coverCommDate = _dtSelect.Rows[0]["CoverageCommenceDate"].ToString();

                        if (DateTime.TryParse(_coverCommDate, out _dtCoverCommDate))
                        {
                            lblCoverCommencementDate.Text = _dtCoverCommDate.ToString("dd/MMM/yyyy");
                           
                            if (DateTime.Compare(dateTimeNow, _dtCoverCommDate) > 0)
                            {
                                lblCommenceDateStatus.Text = "0";
                                lblCommenceDateStatusMessage.Text = Resources.General.CommencementOVER;
                                lblCommenceDateStatusMessage.Font.Bold = true;
                                lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;
                            }
                            else
                            {
                                lblCommenceDateStatus.Text = "1";
                                lblCommenceDateStatusMessage.Text = Resources.General.CommencementOK;
                                lblCommenceDateStatusMessage.Font.Bold = true;
                                lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Green;
                            }
                        }
                        else
                        {
                            lblCommenceDateStatus.Text = "0";
                            lblCommenceDateStatusMessage.Text = Resources.General.CommencementNOTVALID;
                            lblCommenceDateStatusMessage.Font.Bold = true;
                            lblCommenceDateStatusMessage.ForeColor = System.Drawing.Color.Red;
                        }

                        if (_IsAddDriver == true)
                        {
                            lblDriverCount.Text = _dtSelect.Rows[0]["NoOfDriver"].ToString();
                        }
                        else
                        {
                            lblDriverCount.Text = "0";
                        }
                        lblClaimInfo.Text = _IsClaim == true ? "ใช่" : "ไม่มี";

                    }
                    CheckQuoteStatus();
                    _dtSelect = null;
                    _dtSelect = new DataTable("dtSelect");

                    _db = null;
                    _dtSelect = null;

                    divCustomerDetail.Visible = true;
                    divCarDetails.Visible = true;
                    divPolicyDetails.Visible = true;

                    
                }
            }

            ResetCallStatus();


            if (divCompletedQuoteDetails.Visible || divCarDetailList.Visible)
            {
                ddlCICallStatus.Enabled = true;
                divCallStatus.Visible = true;

                CallStatus CI_callstatus = new CallStatus();
                CallStatusDB CI_callstatusdb = new CallStatusDB();
                

                CI_callstatus = CI_callstatusdb.GetCallStatus(Convert.ToInt64(txtCarId.Text), Convert.ToInt64(txtCustomerId.Text), Convert.ToInt32(lblCallType.Text));
                if (CI_callstatus != null)
                {

                    txtCXCRMId.Text = CI_callstatus.CXCRMId.ToString();

                    txtCallBackDateTime.Text = "0";

                    rdoCallFinish.Checked = false;
                    rdoCallBack.Checked = false;
                    rdoFollowUp.Checked = false;

                    if (CI_callstatus.CallFinishType == 1)
                    {
                        rdoCallFinish.Checked = true;
                        lblCallSessionName.Text = "<b style='color:red;'>" + Resources.General.CLOSEDCALL + "</b>";
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.CLOSEDCALL + "');", true);
                    }
                    else if (CI_callstatus.CallFinishType == 2)
                    {
                        rdoCallBack.Checked = true;
                        ddlCBAgentList.Text = CI_callstatus.CallBackAgentID.ToString();
                        txtCallBackDateTime.Text = CI_callstatus.CallBackDateTime.ToString("dd/MMM/yyyy hh:mm tt");
                        lblCallSessionName.Text = "<b style='color:red;'>" + Resources.General.Callback.ToUpper() + "</b> [" + Resources.General.DateTime.ToUpper() + ": " + txtCallBackDateTime.Text + "]";
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.Callback + " [" + Resources.General.DateTime.ToUpper() + ": " + txtCallBackDateTime.Text + "]');", true);
                        DateTime _dtTargetDateTime = dateTimeNow;
                        if (DateTime.TryParse(txtCallBackDateTime.Text, out _dtTargetDateTime))
                        {
                            ddlTDay.Text = _dtTargetDateTime.Day.ToString("00");
                            ddlTMonth.Text = _dtTargetDateTime.Month.ToString("00");
                            ddlTYear.Text = _dtTargetDateTime.Year.ToString("0000");
                            ddlTHour.Text = _dtTargetDateTime.Hour.ToString("00");
                            ddlTMin.Text = _dtTargetDateTime.Minute.ToString("00");
                        }
                        else
                        {
                            txtCallBackDateTime.Text = "0";
                        }
                    }
                    else if (CI_callstatus.CallFinishType == 3)
                    {
                        rdoFollowUp.Checked = true;
                        lblCallSessionName.Text = "<b style='color:blue;'>" + Resources.General.FollowUp.ToUpper() + "</b>";
                        ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.LastCallStatus.ToUpper() + " : " + lblCallTypeDesc.Text + " - " + Resources.General.FollowUp.ToUpper() + "');", true);
                    }

                    rdoCallFinish_CheckedChanged(null, null);
                    if (ddlCIMainCallStatus.Items.Count > 0)
                    {
                        ddlCIMainCallStatus.Text = CI_callstatus.MainCallStatusTypeID.ToString();
                        ddlCIMainCallStatus_SelectedIndexChanged(null, null);

                        if (ddlCICallStatus.Items.Count > 0)
                        {
                            ddlCICallStatus.Text = CI_callstatus.CallStatusTypeID.ToString();
                        }
                    }

                    txtCallStatus.Text = Server.HtmlDecode(CI_callstatus.Remark);
                    lblLastCallStatusMessage.Text = Resources.General.FOUND + " [" + Resources.General.LastDateTime + ": " + CI_callstatus.ModifiedDate.ToString("dd/MMM/yyyy hh:mm tt") + "]";
                }
                else
                {
                    lblLastCallStatusMessage.Text = Resources.General.NEW;
                    lblCallSessionName.Text = Resources.General.NEWCALLPENDING;
                    ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblCallTypeDesc.Text + " - " + Resources.General.NEWCALLPENDING + "');", true);
                   
                }



                CI_callstatus = null;
                CI_callstatusdb = null;
            }
        }
    }

    
    private void ResetCallStatus()
    {
        rdoCallFinish.Checked = true;
        rdoFollowUp.Checked = false;
        rdoCallBack.Checked = false;
        rdoCallFinish_CheckedChanged(null, null);
        ddlCIMainCallStatus.SelectedIndex = 0;
        ddlCIMainCallStatus_SelectedIndexChanged(null, null);
        txtCallStatus.Text = string.Empty;
        txtCallStatusId.Text = "-1";
        txtCXCRMId.Text = "0";
    }

    private void SetGVCarDetailSelectedIndex(Int64 CarID)
    {
        bool _foundStatus = false;
        foreach (GridViewRow myRow in gvCarDetailList.Rows)
        {
            Int64 _carid = Convert.ToInt64(gvCarDetailList.DataKeys[myRow.RowIndex][0]);
            
            if (_carid == CarID)
            {
                gvCarDetailList.SelectedIndex = myRow.RowIndex;
                gvCarDetailList_SelectedIndexChanged(null, null);
                _foundStatus = true;
                break;
            }
           
        }

        if (_foundStatus == false)
        {
            gvCarDetailList.SelectedIndex = 0;
            gvCarDetailList_SelectedIndexChanged(null, null);
        }
    }

    private void CheckApplicationStatus()
    {
        MyDatabase _db = new MyDatabase();
        SortedList _paraList = new SortedList();
        _paraList.Add("@CECarID", txtCarId.Text);
        _paraList.Add("@CustomerID", txtCustomerId.Text);
        DataTable _dtApp = new DataTable("tblApp");
        _dtApp = _db.GetDataTableBySP("sprocCXCRMNonGGApplicationStatusSelectItem", _paraList);

        if (_dtApp != null && _dtApp.Rows.Count > 0)
        {
            SetGVPremiumSelectedIndex();

            lblCarMoreDetailID.Text = _dtApp.Rows[0]["CECarMoreDetailId"].ToString();
            lblAppStatus.Text = string.Empty;
            lblAppStatus.Text = "COM_ID:" + _dtApp.Rows[0]["ProviderCompanyId"].ToString();
            lblAppStatus.Text += "<br/>Payment Status:" + _dtApp.Rows[0]["PaymentStatus"].ToString();
            lblAppStatus.Text += "<br/>Payment Type:" + _dtApp.Rows[0]["PaymentType"].ToString();
            lblAppStatus.Text += "<br/>Quote Ref. No.:" + _dtApp.Rows[0]["QuoteRefNo"].ToString();
            lblAppStatus.Text += "<br/>Date/Time:" + _dtApp.Rows[0]["ModifiedDate"].ToString();
            lblAppStatus.Text += "<br/>AgentID" + _dtApp.Rows[0]["AgentID"].ToString();

            lblAppStatusMessage.Text = string.Empty;
            lblAppStatusMessage.Text = Resources.General.NonGGFoundAppDetailSubmission;
            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;

            lblCarMoreDetailID.Visible = false;
            lblAppStatus.Visible = false;
            
        }
       
    }

    private void SetGVPremiumSelectedIndex()
    {
        foreach (GridViewRow myRow in grvPremiumList.Rows)
        {
            string _selectStatus = myRow.Cells[11].Text.ToString();
           
            if (_selectStatus == "Yes")
            {
                grvPremiumList.SelectedIndex = myRow.RowIndex;
                myRow.Cells[10].ForeColor = System.Drawing.Color.Red;
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + Resources.General.NonGGPackageApplication + "');", true);
                divResult.Visible = false;
                break;
            }
            
        }

        if (grvPremiumList.Rows.Count > 0)
        {
            lblAppStatusMessage.Text = "( " + grvPremiumList.Rows.Count.ToString() + " ) record(s) found.";
            lblAppStatusMessage.ForeColor = System.Drawing.Color.Red;
            lblAppStatusMessage.Font.Bold = true;
        }
        else
        {
            lblAppStatusMessage.Text = string.Empty;
        }
    }

    protected void ResetAll()
    {
        txtCarId.Text = "";
        txtCustomerId.Text = "";
        txtCarPolicyId.Text = "";
        hplReRunQuote.NavigateUrl = "";
        hplNewQuote.NavigateUrl = "";

        lblCallStatusMessage.Text = "";
        divLinks.Visible = false;
        divResult.Visible = false;
        divCallStatus.Visible = false;
        divCustomerDetail.Visible = false;
        divCarDetails.Visible = false;
        divPolicyDetails.Visible = false;
        divCompletedQuoteDetails.Visible = false;
        divCallHistory.Visible = false;
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        Response.Redirect("ViewCICustomerCallNew.aspx?calltype=" + lblCallType.Text);
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect(lblResetUrl.Text.ToString());
    }

    protected void btnCallStatus_Click(object sender, EventArgs e)
    {
        lblCallStatusMessage.Text = "";
        lblLastCallStatusMessage.Text = "";
        Page.Validate();
        if (Page.IsValid)
        {
            if (txtCarId.Text.Length > 0 && txtCustomerId.Text.Length > 0)
            {

                CallStatus callstatus = new CallStatus();
                CallStatusDB callstatusdb = new CallStatusDB();
                if (txtCXCRMId.Text.Length > 0 && txtCXCRMId.Text != "0")
                {
                    callstatus.CXCRMId = Convert.ToInt64(txtCXCRMId.Text);
                }
                else
                {
                    callstatus.CXCRMId = 0;
                }
                callstatus.CarId = Convert.ToInt64(txtCarId.Text);
                if (Session[CE.Global.General.CarResultId] != null)
                {
                    callstatus.CarResultId = Convert.ToInt64(Session[CE.Global.General.CarResultId].ToString());
                }
                callstatus.CustomerId = Convert.ToInt64(txtCustomerId.Text);
                callstatus.AgentId = Convert.ToInt64(txtAgentId.Text);

                callstatus.AgentLeadId = Convert.ToInt64(lblAgentLeadID.Text);
                if (rdoCallFinish.Checked)
                {
                    callstatus.CallFinishType = 1;
                }
                else if (rdoCallBack.Checked)
                {
                    callstatus.CallBackDateTime = Convert.ToDateTime(txtCallBackDateTime.Text);
                    callstatus.CallBackAgentID = Convert.ToInt64(ddlCBAgentList.Text);
                    callstatus.CallFinishType = 2;
                }
                else if (rdoFollowUp.Checked)
                {
                    callstatus.CallFinishType = 3;
                }

                callstatus.MainCallStatusTypeID = Convert.ToInt32(ddlCIMainCallStatus.Text);

                callstatus.CallStatusTypeID = Convert.ToInt32(ddlCICallStatus.Text);
                callstatus.CallTypeId = Convert.ToInt32(lblCallType.Text);
                callstatus.StartDateTime = Convert.ToDateTime(lblStartDateTime.Text);
                callstatus.Remark = Server.HtmlEncode(txtCallStatus.Text);
                callstatus.CXCRMId = callstatusdb.Insert(callstatus);
                if (callstatus.CXCRMId > 0)
                {
                    if (txtCXCRMId.Text.Length > 0 && txtCXCRMId.Text != "0")
                    {
                        lblCallStatusMessage.Text = Resources.General.UPDATE + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }
                    else
                    {
                        txtCXCRMId.Text = callstatus.CXCRMId.ToString();
                        lblCallStatusMessage.Text = Resources.General.SUCCESS + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    }

                    lblCallDurationTimer.Visible = false;


                    gvCarDetailList.Enabled = false;
                    gvCarResult.Enabled = false;

                    lblCallStatusMessage.Text += ", " + Resources.General.CallDuration + ": " + GetCallDuration();
                    btnNext.Visible = true;
                    btnCallStatus.Enabled = false;
                }
                else
                {
                    lblCallStatusMessage.Text = Resources.General.FAIL + " " + dateTimeNow.ToString("dd/MMM/yyyy hh:mm:ss tt");
                }
                callstatus = null;
                callstatusdb = null;
            }
            else
            {
                lblCallStatusMessage.Text = Resources.General.FAIL;
            }
        }
    }

    private string GetCallDuration()
    {
        DateTime _dtStartTime = Convert.ToDateTime(lblStartDateTime.Text);
        TimeSpan _duration = dateTimeNow - _dtStartTime;
        string _strMin = _duration.Minutes.ToString();
        string _strSec = _duration.Seconds.ToString();
        txtMinute.Text = _strMin;
        txtSecond.Text = _strSec;

        if (Convert.ToInt16(_strMin) < 10)
        {
            _strMin = "0" + _strMin;
        }

        if (Convert.ToInt16(_strSec) < 10)
        {
            _strSec = "0" + _strSec;
        }

        return _strMin + " : " + _strSec;
    }

    protected void btnBuyNowRefresh_Click(object sender, EventArgs e)
    {
        Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
        lblResetUrl.Text = lblResetUrl.Text.Replace("&buynowrefresh=true", "");
        Response.Redirect(lblResetUrl.Text + "&buynowrefresh=true");
    }

    protected void gvCarResult_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("BuyNow"))
        {
            if (lblCommenceDateStatus.Text == "1" && lblQuoteDateTimeStatus.Text == "1")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                DataKey myData = gvCarResult.DataKeys[index];

                Session[CE.Global.General.CarResultId] = myData[0].ToString();
                Session[CE.Global.General.ProviderCompanyId] = myData[1].ToString();
                Int64 _resultId = Convert.ToInt64(myData[0].ToString());
                Int64 _companyId = Convert.ToInt64(myData[1].ToString());

                Session[General.CallPageStartDateTime] = lblStartDateTime.Text;
                Session[General.BuyNowCarID] = txtCarId.Text;
                divCarDetailList.Visible = false;

                string _buyurl = myData[2].ToString();
                string proposalURL = CE.Configuration.MyConfigurationManager.GetAppSettingValue("CIServerPath");

                proposalURL = proposalURL + "agentlogin.aspx?" + _buyurl;
                ClientScript.RegisterClientScriptBlock(this.GetType(), "OpenBuyNow", "var myRef = window.open('" + proposalURL + "','mywin','left=20,top=20,width=800,height=600,resizable=1,scrollbars=1');", true);
                divBuyNowStatus.Visible = true;
                divResult.Visible = false;
                divCallStatus.Visible = false;

                hplReRunQuote.Enabled = false;
                hplNewQuote.Enabled = false;
                

                MyDatabase _db = new MyDatabase();
                DataTable _dt = new DataTable("tblSelectedItem");
                SortedList _paraList = new SortedList();
                _paraList.Add("@CarResultID", myData[0].ToString());
                _dt = _db.GetDataTableBySP("sproceCXCRMGetSelectedResultItem", _paraList);
                lblBuyNowStatus.Text = Resources.General.BUYONLINEClickMessage + "<br/>" + Resources.General.CheckAndRefreshMessage;
                if (_dt != null && _dt.Rows.Count > 0)
                {
                    System.Text.StringBuilder _strBuilder = new System.Text.StringBuilder();
                    _strBuilder.Append("<br/><br/><table width='50%' cellspacing='5' cellpadding='5'>");
                    _strBuilder.Append("<tr><td>" + Resources.CarInsurance.CompanyName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CompanyName"].ToString() + "</b></td></tr>");
                    _strBuilder.Append("<tr><td>" + Resources.General.PremiumAmount + "</td><td>:</td><td><b>" + Convert.ToDouble(_dt.Rows[0]["AnnualPremium"].ToString()).ToString("#,000.00") + "</b></td></tr>");
                    _strBuilder.Append("<tr><td>" + Resources.General.PackageName + "</td><td>:</td><td><b>" + _dt.Rows[0]["CoverTypeDesc"].ToString() + "</b></td></tr>");
                  
                    _strBuilder.Append("</table>");
                    lblBuyNowStatus.Text += _strBuilder.ToString();
                }
            }
            else
            {
                
                ShowQuoteStatusAlert();
            }
        }
    }


    private void CheckQuoteStatus()
    {
        lblCommenceDateStatusMessage.Visible = false;
        lblQuoteDateTimeStatusMessage.Visible = false;
        if (lblCommenceDateStatus.Text == "0" && lblQuoteDateTimeStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblCommenceDateStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "1")
        {
            lblQuoteStatusMessage.Text = lblQuoteDateTimeStatusMessage.Text;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else if (lblQuoteDateTimeStatus.Text == "0" && lblCommenceDateStatus.Text == "0")
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.CommencementOVER;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Red;
        }
        else
        {
            lblQuoteDateTimeStatusMessage.Visible = false;
            lblCommenceDateStatusMessage.Visible = false;
            lblQuoteStatusMessage.Text = Resources.General.EverythingOK;
            lblQuoteStatusMessage.Font.Bold = true;
            lblQuoteStatusMessage.ForeColor = System.Drawing.Color.Green;
        }
    }

    private void ShowQuoteStatusAlert()
    {
        if (lblCommenceDateStatus.Text == "0" || lblQuoteDateTimeStatus.Text == "0")
        {
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblQuoteStatusMessage.Text + "');", true);
        }
    }

    protected void gvCarResult_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            foreach (TableCell cell in e.Row.Cells)
            {
                if (cell.HasControls())
                {
                    LinkButton button = cell.Controls[0] as LinkButton;
                    if (button != null)
                    {
                        Image imageSort = new Image();
                        imageSort.ImageUrl = "~/OLD/images/icons/clear.gif";
                        HtmlGenericControl gv = new HtmlGenericControl("div");
                        Label lnkName = new Label();
                        lnkName.Text = button.Text;

                        if (ViewState["SortExpression"] != null && ViewState["SortExpression"].ToString() == button.CommandArgument.ToString())
                        {
                            if (ViewState["SortOrder"] != null && ViewState["SortOrder"].ToString() == SortDirection.Descending.ToString())
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Down.gif";
                            }
                            else
                            {
                                imageSort.ImageUrl = "~/OLD/images/icons/Sort_Up.gif";
                            }
                        }
                        gv.Controls.Add(lnkName);
                        gv.Controls.Add(imageSort);
                        button.Controls.Add(gv);
                    }
                }
            }

            //Creat Custome Header
            GridView HeaderGrid = (GridView)sender;
            GridViewRow HeaderGridRow =
            new GridViewRow(0, 0, DataControlRowType.Header,
            DataControlRowState.Insert);

            TableCell HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src='../images/arrows/arrow-down.png\'  />" + Resources.CarInsuranceResultPage.OwnDamage + "<img src=\"../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "green_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 2;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /> " + Resources.CarInsuranceResultPage.ThirdPartyLiability + "<img src=\"../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" /><br/>" + Resources.CarInsuranceResultPage.PerAccident;
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "blue_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "<img src=\"../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />" + Resources.CarInsuranceResultPage.AdditionalCovers + "<img src=\"../images/arrows/arrow-down.png\" align=\"absmiddle\" alt=\"\" />";
            HeaderCell.Font.Bold = true;
            HeaderCell.ControlStyle.CssClass = "gold_top";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
            HeaderCell.ColumnSpan = 3;
            HeaderGridRow.Cells.Add(HeaderCell);

            HeaderCell = new TableCell();
            HeaderCell.Text = "";
            HeaderCell.HorizontalAlign = HorizontalAlign.Center;
           
            HeaderGridRow.Cells.Add(HeaderCell);

            gvCarResult.Controls[0].Controls.AddAt
            (0, HeaderGridRow);
        }

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            ImageButton ibtBuyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");

            ibtBuyNow.CommandArgument = e.Row.RowIndex.ToString();

            HyperLink _lnkTest = new HyperLink();
            ibtBuyNow.OnClientClick = "javascript:return confirm('" + Resources.General.ConfirmBUYONLINEMessage + "');";
            _lnkTest = null;

        }
    }

    protected void gvCarResult_Sorting(object sender, GridViewSortEventArgs e)
    {
    }

    protected void gvCarResult_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //HIDE
        //For Thailand
        if (e.Row.RowType == DataControlRowType.DataRow)
        {


            string _callCarProviderId = "";

            string _companyId = DataBinder.Eval(e.Row.DataItem, "ProviderCompanyId").ToString();
            ImageButton btnApplyNow = (ImageButton)e.Row.FindControl("ibtBuyNow");
            btnApplyNow.CommandArgument = e.Row.RowIndex.ToString();

            _callCarProviderId = _companyId;

            if (e.Row.DataItem != null)
            {
                _currentRow += 1;
                
            }

            HtmlGenericControl divFrame = new HtmlGenericControl("div");
            divFrame.Attributes.Add("id", "framework_moreinfo");

            HtmlGenericControl divContainer = new HtmlGenericControl("div");
            divContainer.Attributes.Add("id", "container_moreinfo");

            HtmlGenericControl divContent = new HtmlGenericControl("div");
            divContent.Attributes.Add("id", "content_moreinfo");

            Label lblPolicyInfoId = new Label();
            lblPolicyInfoId = (Label)e.Row.FindControl("lblPolicyInfoId");
            object _objPolicyinfoId = 4;//DataBinder.Eval(e.Row.DataItem, "NInfo3");

            Label lblPromoId = new Label();
            lblPromoId = (Label)e.Row.FindControl("lblPromoId");
            object _objPromoId = 11;//DataBinder.Eval(e.Row.DataItem, "NInfo2");

            Label lblPolicyId = new Label();
            lblPolicyId = (Label)e.Row.FindControl("lblPolicyId");
            object _objPolicyId = 5;//DataBinder.Eval(e.Row.DataItem, "NInfo1");

            


            //Company Logo and Cover Type
            Label lblCoverTypeDesc = (Label)e.Row.FindControl("lblPackageName");
            Image imgCompanyLogo = (Image)e.Row.FindControl("imgCompanyLogo");




            string _logoUrl = DataBinder.Eval(e.Row.DataItem, "CompanyLogoServerUrl").ToString();
            string _coverTypeDesc = DataBinder.Eval(e.Row.DataItem, "PackageName").ToString().Trim();

            imgCompanyLogo.ImageUrl = _logoUrl;
            imgCompanyLogo.ToolTip = _coverTypeDesc;
            lblCoverTypeDesc.Text = _coverTypeDesc;
            

            ////CTPL
            Label lblCTPL = (Label)e.Row.FindControl("lblCTPL");
            Label lblCTPLSymbol = (Label)e.Row.FindControl("lblCTPLSymbol");
            Image imgCTPL = (Image)e.Row.FindControl("imgCTPL");
            string _totalCMI = DataBinder.Eval(e.Row.DataItem, "TotalCMI").ToString().Trim();

            if (_totalCMI != null && _totalCMI != string.Empty && Convert.ToSingle(_totalCMI) > 0.0f)
            {
                imgCTPL.Visible = false;
                lblCTPL.Text = _totalCMI;
                lblCTPL.Visible = true;
                lblCTPLSymbol.Visible = true;
            }
            else
            {
                imgCTPL.Visible = true;
                lblCTPL.Text = "0";
                lblCTPL.Visible = false;
                lblCTPLSymbol.Visible = false;
            }
            ////END CTPL

            //// DEC
            Label lblDEC = (Label)e.Row.FindControl("lblDEC");
            Label lblDECSymbol = (Label)e.Row.FindControl("lblDECSymbol");
            Label lblDECZero = (Label)e.Row.FindControl("lblDECZero");
            string _DEC = DataBinder.Eval(e.Row.DataItem, "DEC").ToString().Trim();

            if (_DEC != null && _DEC != string.Empty && Convert.ToSingle(_DEC) > 0.0f)
            {
                lblDECZero.Visible = false;
                lblDEC.Text = _DEC;
                lblDEC.Visible = true;
                lblDECSymbol.Visible = true;
            }
            else
            {
                lblDECZero.Visible = true;
                lblDEC.Text = "0";
                lblDEC.Visible = false;
                lblDECSymbol.Visible = false;
            }
            //// END DEC

            ///SUM INSURED OR OWN DAMAGE FIRE OR THIEF
            Label lblSumInsured = (Label)e.Row.FindControl("lblSumInsured");
            Label lblSumInsuredSymbol = (Label)e.Row.FindControl("lblSumInsuredSymbol");
            Image imgSumInsured = (Image)e.Row.FindControl("imgSumInsured");
            string _sumInsured = DataBinder.Eval(e.Row.DataItem, "SumInsured").ToString().Trim();

            if (_sumInsured != null && _sumInsured != string.Empty && Convert.ToSingle(_sumInsured) > 0.0f)
            {
                imgSumInsured.Visible = false;
                lblSumInsured.Text = Convert.ToInt32(_sumInsured).ToString("#,000"); //_sumInsured;
                lblSumInsured.Visible = true;
                lblSumInsuredSymbol.Visible = true;
            }
            else
            {
                imgSumInsured.Visible = true;
                lblSumInsured.Text = "0";
                lblSumInsured.Visible = false;
                lblSumInsuredSymbol.Visible = false;
            }
            ///END SUM INSURED OR OWN DAMAGE FIRE OR THIEF

            //GARAGE

            
            HyperLink hplnkWorkshop = (HyperLink)e.Row.FindControl("hplWorkshopLink");
          
            hplnkWorkshop.Target = "_blank";
            hplnkWorkshop.Font.Bold = true;
            if (_companyId == "11")
            {
                // "Allianz C.P";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AllianceWorkshopEN");
                }

            }
            else if (_companyId == "12")
            {
                //lblPromo.Text = "MSIG";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGWorkshopEN");
                }
            }
            else if (_companyId == "16")
            {
                //lblPromo.Text = "AXA";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAWorkshopEN");
                }
            }
            else if (_companyId == "29")
            {
                //lblPromo.Text = "LMG Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGWorkshopEN");
                }
            }
            else if (_companyId == "31")
            {
                //lblPromo.Text = "Chartis";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisWorkshopEN");
                }
            }
            else if (_companyId == "32")
            {
                //lblPromo.Text = "Bangkok Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIWorkshopEN");
                }
            }
            else if (_companyId == "33")
            {
                //lblPromo.Text = "MTI Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MTIWorkshopTH");
                }
            }
            else if (_companyId == "41")
            {
                //lblPromo.Text = "Kurnia Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.KurniaWorkShopTH");
                }
            }
            else if (_companyId == "46")
            {
                //lblPromo.Text = "TMS Insurance";
                if (HttpContext.Current.Session["Language"].ToString() == "th-TH")
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopTH");
                }
                else
                {
                    hplnkWorkshop.NavigateUrl = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.TokioWorkShopEH");
                }
            }

            //END GARAGE
        }

    }

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView();
        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + txtCarId.Text]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + txtCarId.Text]);
        }

        gvCarResult.DataSource = dv;
        gvCarResult.DataBind();
    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultCallMeSelectItemList]";
        SortedList _sPara = new SortedList();
        //test
        _sPara.Add("@CarId", txtCarId.Text);

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        if (Convert.ToInt64(txtAgentId.Text) > 0)
        {
            _sPara.Add("@AgentId", Convert.ToInt64(txtAgentId.Text));
        }
        else
        {
            _sPara.Add("@AgentId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        

        if (Session[General.UserId] != null)
        {
            Cache["CarResult" + Session[General.UserId].ToString() + txtCarId.Text] = _dtResult;
        }
        else
        {
            Cache["CarResult" + txtCarId.Text] = _dtResult;
        }

    }


    protected void csvTargetDate_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (rdoCallBack.Checked)
        {
            string _strTargetDateTime = ddlTDay.Text + "/" + ddlTMonth.SelectedItem.Text + "/" + ddlTYear.Text + " " + ddlTHour.Text + ":" + ddlTMin.Text;
            DateTime _dtTargetDateTime = dateTimeNow;

            if (DateTime.TryParse(_strTargetDateTime, out _dtTargetDateTime))
            {
                if (DateTime.Compare(dateTimeNow, _dtTargetDateTime) <= 0)
                {
                    txtCallBackDateTime.Text = _dtTargetDateTime.ToString("dd/MMM/yyyy hh:mm:ss tt");
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                    csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeOlder;
                }
            }
            else
            {
                args.IsValid = false;
                csvTargetDate.ErrorMessage = Resources.General.CallBackDateTimeInvalid;
                txtCallBackDateTime.Text = "0";
            }
        }
    }

    protected void ddlCIMainCallStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCIMainCallStatus.Items.Count > 0 && ddlCIMainCallStatus.SelectedIndex >= 0)
        {
            LoadCallStatusList(Convert.ToInt32(ddlCIMainCallStatus.Text));
        }
    }

    private void LoadMainCallStatusList(int intType)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select MainCallStatusTypeID, " + Resources.DBTable.FieldName + " AS Description from tblCXCRMMainCallStatusType Where [Status] = 1 And [Type] = " + intType.ToString();

            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCIMainCallStatus.Items.Clear();
            ddlCICallStatus.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                for (int i = 0; i < _dtList.Rows.Count; i++)
                {
                    ddlCIMainCallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["MainCallStatusTypeID"].ToString()));
                }
            }
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadMainCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    private void LoadCallStatusList(int MainStatusID)
    {
        try
        {
            MyDatabase _db = new MyDatabase();
            string _strSQL = "Select CallStatusTypeID, " +
                                " '[' + CAST(StatusCode AS VARCHAR) + '] ' + " + Resources.DBTable.FieldName + " AS Description " +
                                " FROM tblCXCRMCallStatusType Where [Status] = 1 And [MainCallStatusTypeID] = " + MainStatusID.ToString();
            DataTable _dtList = new DataTable("tblList");
            _dtList = _db.GetDataTable(_strSQL);
            ddlCICallStatus.Items.Clear();
            ddlCICallStatus.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
            if (_dtList != null && _dtList.Rows.Count > 0)
            {
                for (int i = 0; i < _dtList.Rows.Count; i++)
                {
                    ddlCICallStatus.Items.Add(new ListItem(_dtList.Rows[i]["Description"].ToString(), _dtList.Rows[i]["CallStatusTypeID"].ToString()));
                }
            }
        }
        catch (Exception Ex)
        {
            lblCallSessionName.Text += "<br/><b style='color:red;'>" + Resources.General.ERROR + "</b>: at LoadCallStatusList()<br/>" + Ex.Message + "<br/><br/>" + Ex.StackTrace;
        }
    }

    protected void rdoCallFinish_CheckedChanged(object sender, EventArgs e)
    {
        trCallBack1.Visible = false;
        trCallBack2.Visible = false;
        if (rdoCallFinish.Checked)
        {
            LoadMainCallStatusList(1);
        }
        else if (rdoCallBack.Checked)
        {
            trCallBack1.Visible = true;
            trCallBack2.Visible = true;
            LoadMainCallStatusList(2);
        }
        else if (rdoFollowUp.Checked)
        {
            LoadMainCallStatusList(3);
        }

        if (ddlCIMainCallStatus.Items.Count > 0)
        {
            ddlCIMainCallStatus.SelectedIndex = 0;
            ddlCIMainCallStatus_SelectedIndexChanged(sender, e);
        }
    }

    protected void gvCarDetailList_OnSorted(object sender, EventArgs e)
    {
        if (gvCarDetailList.Rows.Count > 0)
        {
            gvCarDetailList.SelectedIndex = -1;
            divCarDetails.Visible = false;
            divPolicyDetails.Visible = false;
            divResult.Visible = false;
            divLinks.Visible = false;
            divCallStatus.Visible = false;
            divCompletedQuoteDetails.Visible = false;
        }
    }

    protected void gvCarDetailList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (gvCarDetailList.SelectedIndex >= 0)
        {
            GridViewRow _row = gvCarDetailList.SelectedRow;
            ShowCarAndCustomerDetails(Convert.ToInt64(txtCustomerId.Text), Convert.ToInt64(_row.Cells[0].Text), Convert.ToInt64(_row.Cells[1].Text));
            lblCallHistoryFoundCount.Text = "0";
            gvCallHistory.DataBind();
            if (lblCallHistoryFoundCount.Text != "0")
            {
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('" + lblCallHistoryMessage.Text + "');", true);
            }

            divCustomerDetail.Focus();
            
        }
    }

    protected void gvCallHistory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            Int64 value = Convert.ToInt64(e.Row.Cells[2].Text);
          
            if (value.ToString() == txtCarId.Text)
            {
                e.Row.Cells[2].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[2].Font.Bold = true;
                e.Row.Cells[2].Font.Size = FontUnit.Medium;

                e.Row.Cells[4].BackColor = System.Drawing.Color.FromName("#c6c6c6");
                e.Row.Cells[4].Font.Bold = true;
                //e.Row.Cells[4].Font.Size = FontUnit.Medium;
                e.Row.BackColor = System.Drawing.Color.FromName("#ffffcc");
                e.Row.Height = Unit.Pixel(Convert.ToInt32(e.Row.Height.Value + 60d));

                lblCallHistoryFoundCount.Text = (Convert.ToInt32(lblCallHistoryFoundCount.Text) + 1).ToString();
                lblCallHistoryMessage.Text = "(" + lblCallHistoryFoundCount.Text + ") " + Resources.General.Callhistoryfound + "";
                lblCallHistoryFoundCount.Visible = false;
                
            }
            else
            {
                if (lblCallHistoryFoundCount.Text == "0")
                {
                    lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
                }
            }
           
        }
        else if (lblCallHistoryFoundCount.Text == "0")
        {
            lblCallHistoryMessage.Text = Resources.General.Nocallhistoryfor + " " + Resources.CarInsurance.CarId + ": " + txtCarId.Text;
            lblCallHistoryFoundCount.Visible = false;
        }
    }
}
